#include "GameLayer.h"


bool GameLayer::init()
{
	if ( !CCLayer::init() )
    {
        return false;
    }


	this->setTouchEnabled(true);
    winSize = CCDirector::sharedDirector()->getWinSize();
	
	CCLayerColor *p_bgSprite = CCLayerColor::create(ccc4(0,0,0,0));
	this->addChild(p_bgSprite, 0);

	pMenu = CCMenu::create();
	CCLabelTTF* pLabel = CCLabelTTF::create("Pause", "∏º¿∫ ∞ÌµÒ", 40);
	CCMenuItemLabel* pMenuItem = CCMenuItemLabel::create(pLabel, this, menu_selector(GameLayer::popPause));
	pMenuItem->setPosition(ccp(winSize.width * 0.8f, 50));
	//pMenuItem->setColor(ccBLACK);
	pMenu->addChild(pMenuItem);
	pMenu->setPosition(CCPointZero);
	CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(pMenu, kCCMenuHandlerPriority, true);
	this->addChild(pMenu);
    
	lblScore = CCLabelTTF::create("0", "∏º¿∫∞ÌµÒ", 40);
	//lblScore->setColor(ccBLACK); 
	lblScore->setPosition((ccp(350, 1000)));
	this->addChild(lblScore, 10);

	lblCombo = CCLabelTTF::create("0", "∏º¿∫∞ÌµÒ", 40);
	//lblCombo->setColor(ccBLACK); 
	lblCombo->setPosition((ccp(150, 1000)));
	this->addChild(lblCombo, 10);

	lblTime = CCLabelTTF::create("60", "∏º¿∫∞ÌµÒ", 40);
	//lblTime->setColor(ccBLACK); 
	lblTime->setPosition((ccp(400, 1150)));
	this->addChild(lblTime, 10);

	indexBox = IndexBox::create("rec.png", CCRect(0,0,100, 100));
	indexBox->setPosition(ccp(650, 1100));
	
	idxColorId = randomId(5)+1;
    changeIdxColor();

	
	this->addChild(indexBox, 0);

	count = 0;
	scoreCount = 1;
	combo = 0;
	comboState = 0;				//콤보 상태를 나타내는 변수로 마지막 클릭된 시간을 넣어줌
	basicScore = 10;
	
	recNumber = 0;
    int x = 120;
    int y = 200;
    int k = 0;
	int colorCnt = 1;
	score = 0;

	changeCounter = 0;
    for(int i = 0 ; i < 30 ; i++)
    {
        box[i] = Box::create("rec.png", CCRect(0, 0, 120, 120));
        box[i]->setAnchorPoint(CCPointZero);
        box[i]->clickState = false;
		box[i]->imageId = i + 1;
		box[i]->numberId = k + 1;
		box[i]->colorId = colorCnt;
		//box[i]->initWithFile(CCString::createWithFormat("rec_%d.png", box[i]->colorId)->getCString());
        box[i]->setPosition(ccp(x, y));
        k++;
        if(k == 5)
        {
			colorCnt++;
            x = 120;
            y += 130;
            k = 0;
        }
        else
        {
            x += 130;
        }
        
        this->addChild(box[i]);
    }
    
    changeBoxColor();

	timer = 60;
	lblTime->setString(CCString::createWithFormat("%d", timer)->getCString());
	this->schedule(schedule_selector(GameLayer::timeUpdate), 1.0f);
	this->schedule(schedule_selector(GameLayer::comboUpdate), 1.0f); //콤보상태를 초마다 확인함

	//CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(GameLayer::doMsgReceived), "TouchStatus", NULL);

    
	return true;
}

void GameLayer::update(float dt)
{
	//for(int i = 0 ; i < 30; i++)
		//if(box[i]->clickState == true)
	//	{
		//	box[i]->clickState = false;		
		//}
}

void GameLayer::comboUpdate(float dt)  //일정시간내로 클릭을 하지않으면 콤보가 끊긴다.
{
	if(timer <= (comboState - 3)){		// 마지막 클릭시간-3초 3초이다 일단 3초로 했음
		combo = 0;
		lblCombo->setString(CCString::createWithFormat("%d", combo)->getCString());
	}
}

void GameLayer::timeUpdate(float dt)
{
	if(timer == 0)
    {
		this->unschedule(schedule_selector(GameLayer::timeUpdate));
        popResult(score);
	}
    
	else
    {
		timer--;
		lblTime->setString(CCString::createWithFormat("%d", timer)->getCString());
	}
	
}

//bool GameLayer::ccTouchBegan(CCTouch *pTouch, CCEvent* event)
//{
//    CCPoint touchPoint = pTouch->getLocation();
//}

void GameLayer::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent)
{
   
}

void GameLayer::ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent)
{
	/*CCTouch* pTouch = (CCTouch*) pTouches->anyObject();
	CCPoint touchLocation = pTouch->getLocation();
    touchLocation = this->convertToNodeSpace(touchLocation);
	*/
}

void GameLayer::ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent)
{	
	CCTouch* pTouch = (CCTouch*) pTouches->anyObject();
	CCPoint touchLocation = pTouch->getLocation();
	touchLocation = this->convertToNodeSpace(touchLocation);

	CCRect posRect = CCRect(touchLocation.x, touchLocation.y, 0,0);
    
    for(int i = 0 ; i < 30 ; i++){
        if(posRect.intersectsRect(box[i]->boundingBox()))
        {
            if(box[i]->clickState == true){
                return;
            }
            
			if(idxColorId == box[i]->colorId && changeCounter+1 == box[i]->numberId){

				++count;	  //몇개가 클릭됐는지 카운트 다른데 쓰인데가없음

				CCString* sCombo = CCString::createWithFormat("%d", ++combo);
				lblCombo->setString(sCombo->getCString());
				
				//점수계산과정
				if(combo%5 == 0){
					++scoreCount; //점수계산을 위한 카운트
					score = score + scoreCount*basicScore + (100*combo);
				}

				else {
					score = score + basicScore;
				}

				CCString* sScore = CCString::createWithFormat("%d", score);
				lblScore->setString(sScore->getCString());
				//여기까지 점수계산 과정

                box[i]->clickState = true;
				box[i]->initWithFile(CCString::createWithFormat("rec1_%d.png", box[i]->imageId)->getCString());

				++changeCounter;
				SimpleAudioEngine::sharedEngine()->playEffect(CCString::createWithFormat("click_%d.mp3", changeCounter)->getCString());
               	if(changeCounter == 5)
				{
					changeBoxColor();
					changeIdxColor();
					changeCounter = 0;
					clearClickSate();
				}
			}
			else{
				combo = 0;
				CCString* sCombo = CCString::createWithFormat("%d", combo);
				lblCombo->setString(sCombo->getCString());

			}	
        }
    }
	comboState = timer;        //마지막 눌렀던 시간을 콤보상태에 넣어준다.
}

void GameLayer::changeBoxColor()
{
    int idx, old, oldColor, oldNumber;
    
    
    for(int i = 0 ; i < 30 ; i++){
        idx = randomId(30);
        
		old = box[i]->imageId;
        box[i]->imageId = box[idx]->imageId;
		box[idx]->imageId = old;

		oldColor = box[i]->colorId;
		box[i]->colorId = box[idx]->colorId;
		box[idx]->colorId = oldColor;

		oldNumber = box[i]->numberId;
		box[i]->numberId = box[idx]->numberId;
		box[idx]->numberId = oldNumber;
        
        box[i]->initWithFile(CCString::createWithFormat("rec_%d.png", box[i]->imageId)->getCString());
        box[idx]->initWithFile(CCString::createWithFormat("rec_%d.png", box[idx]->imageId)->getCString());

    }

}

void GameLayer::changeIdxColor()
{
	idxColorId = randomId(5) + 1;
	indexBox->indexColorId = idxColorId;
    indexBox->initWithFile(CCString::createWithFormat("idx_%d.png", idxColorId)->getCString());
	
}

int GameLayer::randomId(int val)
{
	srand(time(NULL));
	int number = arc4random()%val;
	return number;
}


void GameLayer::clearClickSate()
{
    for(int i = 0 ; i < 30 ; i++){
        box[i]->clickState = false;
    }
}

void GameLayer::popPause(CCObject* pSender)
{
	CCDirector::sharedDirector()->pause();
    CCScene* popPause = PauseLayer::scene(this);
    this->addChild(popPause, 2000, 2000);
}

void GameLayer::popResult(int score)
{
	CCDirector::sharedDirector()->pause();
    CCScene* popResult = ResultLayer::scene(this);
    this->addChild(popResult, 2000, 2000);
}

//void GameLayer::doMsgReceived(CCObject* obj)
//{
//    CCString* pParam = (CCString*) obj;
//    
//    if(pParam->intValue() == 1)
//    {
//        CCDirector::sharedDirector()->resume();
//        
//		this->setTouchEnabled(true);
//        //CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, this);
//        CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(pMenu, kCCMenuHandlerPriority, true);
//    }
//    else
//    {
//        CCDirector::sharedDirector()->pause();
//        
//		this->setTouchEnabled(false);
//        //CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
//		CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(pMenu);
//        
//    }
//    
//    
//}